var express = require('express')
var path = require('path')
var cookieParser = require('cookie-parser')
var logger = require('morgan')
const cors = require('cors')
const { jwtAuth } = require('./utils/user-jwt')

var usersRouter = require('./routes/users')
var dashboardRouter = require('./routes/dashboard')
var categoriesRouter = require('./routes/categories')
var loginRouter = require('./routes/login')
var aditorRouter = require('./routes/aditor')
var articlesRouter = require('./routes/articles')
var blogloginRouter = require('./routes/bloglogin')
var blogcontentRouter = require('./routes/blogcontent')
var messagesRouter = require('./routes/messages')
var fontarticleRouter = require('./routes/font-article')
var fontuserRouter = require('./routes/font-user')

var app = express()

app.use(logger('dev'))
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(cookieParser())
app.use(express.static(path.join(__dirname, 'public')))
app.use('/uploads', express.static(path.join(__dirname + '/uploads')))

app.use(cors())

app.use('/bloglogin', blogloginRouter)
app.use('/blogcontent', blogcontentRouter)
app.use('/messages', messagesRouter)
app.use('/fontarticle', fontarticleRouter)
app.use('/fontuser', fontuserRouter)
app.use('/aditor', aditorRouter)

//全局验证,如果token过期,提示错误
app.use(jwtAuth, (err, req, res, next) => {
  //判断是否由 Token 解析失败导致的
  if (err.name == 'UnauthorizedError') {
    return res.send({
      status: 401,
      message: '登录凭证失效,请重新登录!',
    })
  }
  res.send({
    status: 500,
    message: '未知的错误!',
  })
})

app.use('/users', usersRouter)
app.use('/dashboard', dashboardRouter)
app.use('/categories', categoriesRouter)
app.use('/login', loginRouter)
app.use('/articles', articlesRouter)

module.exports = app
